package org.example.bookingsystem.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.example.bookingsystem.client.UserClient;
import org.example.bookingsystem.common.Constants;
import org.example.bookingsystem.model.Result;
import org.example.bookingsystem.model.UserInfo;
import org.example.bookingsystem.service.UserService;
import org.example.bookingsystem.utils.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public Result login(String userName, String password) {
/**
 * 1. 参数校验
 * 2. 密码校验
 * 3. 生成token, 并返回
 */
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
            return Result.fail("用户名或密码为空");
        }
        //获取数据库中的密码
        UserInfo userInfo = userService.queryByUserName(userName);
        if (userInfo==null || userInfo.getUid()<0){
            return Result.fail("用户不存在");
        }
        if (!password.equals(userInfo.getPassword())){
            return Result.fail("密码错误!");
        }

        //生成token, 并返回
        Map<String, Object> claim = new HashMap<>();
        claim.put("id", userInfo.getUid());
        claim.put("name", userInfo.getUserName());
        String token = JwtUtils.genToken(claim);
        return Result.success(token);
    }
    @Autowired
    private UserClient userClient;
    @RequestMapping("/queryInfo")
    public Result queryInfo() {
        int tid = userClient.advice();
        String msg = "推荐购买的票编号为:"+tid;
       return Result.success1(userClient.sendQuery(),msg);
    }
    @RequestMapping("isAccept")
    public Result isAccept(String accept){
//        log.warn("发送成功");
        return Result.success(userClient.accept(accept));
    }
    @RequestMapping("pay")
    public Result pay(int type, int tid,HttpServletRequest request){
        String token = request.getHeader("user_token");
        int uid = JwtUtils.getUserIdFromToken(token);
        String msg = uid+","+tid+","+type;
        //log.error("msg:"+msg);
        return Result.success(userClient.pay(msg));
    }


}

